package com.momoauth.api_client.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.momoauth.api_client.entity.Groups;
import com.momoauth.api_client.entity.User;
import com.momoauth.api_client.entity.User_Group;
import com.momoauth.api_client.mapper.GroupsMapper;
import com.momoauth.api_client.mapper.UserGroupMapper;
import com.momoauth.api_client.mapper.UserMapper;
import com.momoauth.common.core.result.ResponseResurt;
import com.momoauth.common.security.annotation.RequiresRoles;
import com.momoauth.common.security.enumeration.Logical;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/group")
@Api(tags = "群组")
@RequiresRoles(value = {"超级管理员","普通管理员"}, logical = Logical.OR)
public class GroupController {

    @Resource
    GroupsMapper groupsMapper;

    @Resource
    UserGroupMapper userGroupMapper;

    @Resource
    UserMapper userMapper;

    /**
     * 群组列表
     * @param groups
     * @return
     */
    @ApiOperation(value = "群组列表")
    @RequestMapping(value = "/getGroupList", method = RequestMethod.GET)
    public ResponseResurt getGroupList(Groups groups) {
        QueryWrapper<Groups> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("isDelete", 0);
        queryWrapper.orderByDesc("groupId"); //按主键倒序排序
        Page<Groups> page = new Page<>(groups.getCurrentPage(), groups.getPageSize());
        page.setRecords(groupsMapper.getGroupList(page, queryWrapper));
        return ResponseResurt.success().data(page);
    }

    /**
     * 创建群组
     * @param groups
     * @param bindingResult
     * @return
     */
    @ApiOperation(value = "创建群组")
    @ApiImplicitParam(name = "groupName", value = "群组名称", required = true)
    @RequestMapping(value = "/createGroup", method = RequestMethod.POST)
    public ResponseResurt createGroup(
            @Validated Groups groups,
            BindingResult bindingResult
    ) {
        // 非法参数验证
        if(bindingResult.hasErrors()){
            String errorMsg = bindingResult.getFieldError().getDefaultMessage();
            return ResponseResurt.error().msg(errorMsg);
        }
        // 执行新增操作
        int isInsert = groupsMapper.insert(groups);
        if (isInsert > 0) {
            return ResponseResurt.success().msg("恭喜您，创建成功。");
        }
        return ResponseResurt.error().msg("很抱歉，创建失败！");
    }

    /**
     * 修改群组
     * @param groups
     * @param bindingResult
     * @return
     */
    @ApiOperation(value = "修改群组")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupId", value = "群组ID（主键）", required = true),
            @ApiImplicitParam(name = "groupName", value = "群组名称", required = true)
    })
    @RequestMapping(value = "/updateGroup", method = RequestMethod.GET)
    public ResponseResurt updateGroup(
            @Validated Groups groups,
            BindingResult bindingResult
    ) {
        // 非法参数验证
        if(bindingResult.hasErrors()){
            String errorMsg = bindingResult.getFieldError().getDefaultMessage();
            return ResponseResurt.error().msg(errorMsg);
        }
        // 查询当前版本号
        long version = groupsMapper.selectById(groups.getGroupId()).getVersion();
        groups.setVersion(version);
        // 执行更新操作
        int isUpdate = groupsMapper.updateById(groups);
        if (isUpdate > 0) {
            return ResponseResurt.success().msg("恭喜您，修改成功。");
        }
        return ResponseResurt.error().msg("很抱歉，修改失败！");
    }

    /**
     * 删除群组
     * @param groups
     * @return
     */
    @ApiOperation(value = "删除群组")
    @ApiImplicitParam(name = "groupId", value = "群组ID（主键）", required = true)
    @RequestMapping(value = "/deleteGroup", method = RequestMethod.GET)
    public ResponseResurt deleteGroup(Groups groups) {
        // 判断是否有用户正在使用该群组
        Integer isExist = userGroupMapper.existUseGroup(groups.getGroupId());
        if (isExist != null) {
            return ResponseResurt.error().msg("存在用户使用该群组，无法删除。");
        }
        // 执行删除操作（逻辑删除）
        int isDelete = groupsMapper.deleteGroupById(groups.getGroupId());
        if (isDelete > 0) {
            return ResponseResurt.success().msg("恭喜您，删除成功。");
        }
        return ResponseResurt.error().msg("很抱歉，删除失败！");
    }

    /**
     * 群组详情
     * @param groups
     * @return
     */
    @ApiOperation(value = "查看群组信息")
    @ApiImplicitParam(name = "groupId", value = "群组ID（主键）", required = true)
    @RequestMapping(value = "/getGroupById", method = RequestMethod.GET)
    public ResponseResurt getGroupById(Groups groups) {
        groups = groupsMapper.selectById(groups.getGroupId());
        return ResponseResurt.success().data(groups);
    }

    /**
     * 使用该群组的用户列表
     * @param user
     * @return
     */
    @ApiOperation(value = "使用该群组的用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "当前页码", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页数", required = true),
            @ApiImplicitParam(name = "group_id", value = "群组ID（外键）", required = true)
    })
    @RequestMapping(value = "/getUserListFromGroup", method = RequestMethod.GET)
    public ResponseResurt getUserListFromGroup(User user, Integer group_id) {
        Page<User> page = new Page<>(user.getCurrentPage(),user.getPageSize());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_id", group_id);
        queryWrapper.eq("isDelete", 0);
        page.setRecords(userGroupMapper.getUserListFromGroup(page, queryWrapper));
        return ResponseResurt.success().data(page);
    }

    /**
     * 删除用户群组
     * @param user_group
     * @return
     */
    @ApiOperation(value = "删除用户群组")
    @ApiImplicitParam(name = "id", value = "用户群组ID（主键）", required = true)
    @RequestMapping(value = "/deleteUserGroup", method = RequestMethod.GET)
    public ResponseResurt deleteUserGroup(User_Group user_group) {
        // 执行操作（物理删除）
        int isDelete = userGroupMapper.deleteById(user_group.getId());
        if (isDelete > 0) {
            return ResponseResurt.success().msg("恭喜您，删除成功。");
        }
        return ResponseResurt.error().msg("很抱歉，删除失败！");
    }

    /**
     * 可用的用户列表
     * @param user
     * @return
     */
    @ApiOperation(value = "可用的用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "当前页码", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页数", required = true)
    })
    @RequestMapping(value = "/getUserList", method = RequestMethod.GET)
    public ResponseResurt getUserList(User user) {
        Page<User> page = new Page<>(user.getCurrentPage(),user.getPageSize());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        queryWrapper.eq("isDelete", 0);
        page.setRecords(userMapper.getUserList(page, queryWrapper));
        return ResponseResurt.success().data(page.getRecords());
    }

    /**
     * 加入群组
     * @param user_group
     * @return
     */
    @RequestMapping(value = "/addUserGroup", method = RequestMethod.POST)
    @ApiOperation(value = "加入群组")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user_id", value = "用户ID（外键）", required = true),
            @ApiImplicitParam(name = "group_id", value = "群组ID（外键）", required = true)
    })
    public ResponseResurt addUserGroup(User_Group user_group) {
        // 判断是否重复加入群组
        Integer isExist = userGroupMapper.ifRepeatJoinGroup(user_group);
        if (isExist != null) {
            return ResponseResurt.error().msg("该用户已加入目标群组。");
        }
        // 执行新增操作
        int isInsert = userGroupMapper.insert(user_group);
        if (isInsert > 0) {
            return ResponseResurt.success().msg("恭喜您，加入成功。");
        }
        return ResponseResurt.error().msg("很抱歉，加入失败！");
    }
}
